<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2019/6/5
 * Time: 23:05
 */

namespace app\Module\Index\Controller;


use app\Module\Index\Logic\MessageLogic;
use app\Module\Index\Logic\MessageType;
use app\Module\Index\Model\CircleModel;
use app\Module\Index\Model\CirclePhotoModel;
use app\Module\Index\Model\CirclePhotoTypeModel;
use app\Module\Index\Model\LogCirclePhotoShareModel;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\FFMpeg;

class CirclePhotoController extends CheckAuth
{
    private $videoPath = APP_PATH . '/upload/video/';

    /**
     * 添加圈子
     *
     * @verify int $circle_photo_type_id
     * @verify string $resource
     * @verify string $resource_type
     * @verify string $title 标题
     * @verify string|null $content 内容
     * @return string
     */
    public function addAction($circle_photo_type_id, $resource, $resource_type, $content, $title)
    {
        $circleModel = new CircleModel();
        $circleData  = $circleModel->row(['user_id' => $this->userId,]);
        if (empty($circleData)) {
            return fail('未加入圈子');
        }
        $circle_id = $circleData['id'];

        $frame_url = '';
        if ($resource_type == 'video') {
            // 添加视频缩略图
            $ffmpeg    = FFMpeg::create([
                'ffmpeg.binaries'  => '/usr/bin/ffmpeg',
                'ffprobe.binaries' => '/usr/bin/ffprobe',
                'timeout'          => 3600, // The timeout for the underlying process
                'ffmpeg.threads'   => 12,   // The number of threads that FFMpeg should use
            ]);
            $videoObj  = $ffmpeg->open(APP_PATH . str_replace('https://www.clocir.com', '', $resource));
            $imageName = basename($resource, ".mp4");
            $imageUrl  = $this->videoPath . $imageName;
            $videoObj->frame(TimeCode::fromSeconds(1))->save($imageUrl . '.jpg');
            $frame_url = 'https://www.clocir.com/upload/video/' . $imageName . '.jpg';
        }

        $circlePhotoModel     = new CirclePhotoModel();
        $id                   = $circlePhotoModel->insert([
            'circle_id'            => $circle_id,
            'circle_photo_type_id' => $circle_photo_type_id,
            'resource'             => $resource,
            'resource_type'        => $resource_type,
            'frame_url'            => $frame_url,
            'title'                => $title,
            'content'              => $content,
            'created'              => now(),
        ]);
        $circlePhotoTypeModel = new CirclePhotoTypeModel();
        $circlePhotoTypeModel->addSet('num=num+1');
        $circlePhotoTypeModel->addWhere([
            'id' => $circle_photo_type_id,
        ]);
        $circlePhotoTypeModel->update();

        return success($id);
    }

    /**
     * 获取照片
     *
     * @verify int $id
     * @return string
     */
    public function getAction($id)
    {
        $circlePhotoModel = new CirclePhotoModel();
        $circlePhotoModel->setJoin('circle', 'circle.id = circle_photo.circle_id');
        $circlePhotoModel->setFields([
            'circle.name', 'circle.logo', 'circle_photo.id', 'circle_photo.resource',
            'circle_photo.resource_type', 'circle_photo.content', 'circle_photo.look_num',
            'circle_photo.collect_num', 'circle_photo.comment_num', 'circle_photo.share_num',
            'circle_photo.created', 'circle_photo.circle_id', 'circle_photo.title', 'circle_photo.frame_url',
        ]);
        $data = $circlePhotoModel->row([
            'circle_photo.is_hide' => 0,
            'circle_photo.id'      => $id,
        ], 600);

        return success($data);
    }

    /**
     * 删除照片
     *
     * @verify int $id
     * @return string
     */
    public function deleteAction($id)
    {
        $circleModel = new CircleModel();
        $circleData  = $circleModel->row(['user_id' => $this->userId,]);
        if (empty($circleData)) {
            return fail('未加入圈子');
        }
        $circle_id        = $circleData['id'];
        $circlePhotoModel = new CirclePhotoModel();
        $circlePhotoData  = $circlePhotoModel->row([
            'circle_id' => $circle_id,
            'id'        => $id,
        ]);
        $result           = $circlePhotoModel->update([
            'is_hide' => 1,
        ], [
            'circle_id' => $circle_id,
            'id'        => $id,
        ]);

        if (empty($result)) {
            return fail('删除失败');
        } else {
            $circlePhotoTypeModel = new CirclePhotoTypeModel();
            $circlePhotoTypeModel->addSet('`num` = `num`-1');
            $circlePhotoTypeModel->update([
            ], [
                'circle_id' => $circle_id,
                'id'        => $circlePhotoData['circle_photo_type_id'],
            ]);
        }

        return success($result);
    }

    /**
     * 获取照片列表
     *
     * @verify int $circle_photo_type_id
     * @verify int $page
     * @verify int $limit
     * @return string
     */
    public function getListAction($circle_photo_type_id, $page = 1, $limit = 10)
    {
        $circlePhotoModel = new CirclePhotoModel();
        $circlePhotoModel->addOrder('created', false);
        $circlePhotoModel->setPage($page, $limit);
        $data = $circlePhotoModel->select([
            'circle_photo_type_id' => $circle_photo_type_id,
            'is_hide'              => 0,
        ], 600);

        return success($data);
    }

    /**
     * 获取最新照片
     *
     * @param     $circle_id
     * @param int $page
     * @param int $limit
     * @return string
     */
    public function getNewListAction($circle_id, $page = 1, $limit = 3)
    {
        $circlePhotoModel = new CirclePhotoModel();
        $circlePhotoModel->addWhere([
            'circle_id' => $circle_id,
            'is_hide'   => 0,

        ]);
        $circlePhotoModel->addOrder('created', false);
        $circlePhotoModel->setPage($page, $limit);
        $data = $circlePhotoModel->select([], 600);

        return success($data);
    }

    /**
     * 根据类型获取照片
     *
     * @verify int    $type_id
     * @verify string|null $name
     * @verify int|null $page
     * @verify int|null $limit
     * @return string
     */
    public function getListByTypeAction($type_id, $name = '', $page = 1, $limit = 3)
    {
        $circlePhotoModel = new CirclePhotoModel();
        $circlePhotoModel->setTableByname('cp_');
        $circlePhotoModel->setFields('cp_.*,cir_.name as circle_name,cir_.logo');
        $circlePhotoModel->setJoin('circle AS cir_', 'cp_.circle_id = cir_.id');
        $circlePhotoModel->setJoin('circle_type AS ct_', 'ct_.circle_id = cp_.circle_id');

        $circlePhotoModel->addWhere([
            'is_hide'    => 0,
            'cir_.audit' => 'pass',
        ]);
        if ($type_id == -1) {
        } else {
            $circlePhotoModel->addWhere([
                'ct_.one_type_id' => $type_id,
            ]);
        }

        if (!empty($name)) {
            $circlePhotoModel->addLike('cp_.title', $name, 'AND (');
            $circlePhotoModel->addLike('cp_.content', $name, 'OR');
//            $circlePhotoModel->addLike('ct_.name', $name, 'OR');
            $circlePhotoModel->addWhere(' )');
        }

        $circlePhotoModel->addGroup('cp_.id');
        $circlePhotoModel->addOrder('cp_.score', false);
        $circlePhotoModel->setPage($page, $limit);
        $data = $circlePhotoModel->select([], 600);

        return success($data);
    }

    /**
     * 添加圈子分享量
     * @verify int $circle_photo_id
     * @return string
     */
    public function addShareNumAction($circle_photo_id)
    {
        $logCirclePhotoShareModel = new LogCirclePhotoShareModel();
        $logCirclePhotoShareModel->addWhere('created', date("Y-m-d", strtotime("-1 hour")), '>=');
        $logCirclePhotoShareModel->addWhere([
            'circle_photo_id' => $circle_photo_id,
            'user_id'         => $this->userId,
        ]);
        $shareNum = $logCirclePhotoShareModel->count('1', null, 600);
        // 每个用户每小时只能增加一个
        if ($shareNum > 0) {
            return success();
        }

        $logCirclePhotoShareModel->insert([
            'circle_photo_id' => $circle_photo_id,
            'user_id'         => $this->userId,
            'created'         => now(),
        ]);

        $circlePhotoModel = new CirclePhotoModel();
        $data             = $circlePhotoModel->row(['id' => $circle_photo_id]);

        $circleModel = new CircleModel();
        $circleData  = $circleModel->row(['id' => $data['circle_id']]);


        $messageLogic = new MessageLogic();
        $messageLogic->add($this->userId, $circleData['user_id'], $circle_photo_id, MessageType::CIRCLE_PHOTO_SHARE, $data['title']);


        $circlePhotoModel->update('share_num=share_num+1', ['id' => $circle_photo_id]);
        return success();
    }
}